package com.contract.spirit.ui.invite

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import com.contract.commonlib.util.ext.setOnSingleClickListener
import com.contract.commonlib.base.BaseActivity
import com.contract.commonlib.callback.OnSavePictureListener
import com.contract.commonlib.util.BitmapUtils
import com.contract.commonlib.util.CommonUtils
import com.contract.commonlib.util.ToolUtils
import com.contract.commonlib.util.ZXingUtils
import com.contract.commonlib.util.ext.showToast
import com.contract.spirit.R
import com.contract.spirit.databinding.ActivityInviteBinding
import com.contract.spirit.manage.CommonConfigManager

/**
 * @author: witness
 * created: 2021/9/28
 * desc:
 */
class InviteActivity : BaseActivity<ActivityInviteBinding,InviteViewModel>() {
    lateinit var inviteUrl:String
    override fun setContentView(): Int {
        return R.layout.activity_invite
    }

    override fun initData() {
        bindInviteInfo()
        mBinding.btnSave.setOnSingleClickListener {
            showLoading(true,"保存中...")
            val view2Bitmap = BitmapUtils.view2Bitmap(mBinding.vgContent)
            savaShareBitmap(view2Bitmap)
        }
        mBinding.btnCopy.setOnSingleClickListener {
            ToolUtils.copyToClip(mContext,inviteUrl)
            showToast("复制成功")
        }
    }

    @SuppressLint("SetTextI18n")
    private fun bindInviteInfo() {
        mBinding.apply {
            inviteUrl = CommonConfigManager.configInfoResponse.registerUrl
            val inviteCode = CommonConfigManager.userInfoResponse.inviteCode
            if (!inviteUrl.contains("?")) {
                inviteUrl = "$inviteUrl?inviteCode=$inviteCode"
            }
            tvInviteCode.text = "邀请码：$inviteCode"
            val createQRImage = ZXingUtils.createQRImage(
                inviteUrl,
                CommonUtils.getDimension(R.dimen.dp_90),
                CommonUtils.getDimension(R.dimen.dp_90)
            )
            ivCode.setImageBitmap(createQRImage)
        }
    }

    private fun savaShareBitmap(shareBitmap: Bitmap) {
        BitmapUtils.savePicture(mContext, shareBitmap, object : OnSavePictureListener{
           override fun onPrepare() {}
            override  fun onFinish() {
                showContent()
            }
            override  fun onSuccess() {
                showContent()
                showToast("保存成功")
            }
        })
    }

    companion object{
        fun launch(mContext: Context){
            mContext.startActivity(
                Intent(
                    mContext,
                    InviteActivity::class.java
                )
            )
        }
    }
}